package org.answer.controller;


import org.answer.constant.MessageConstant;
import org.answer.constant.RedisConstant;
import org.answer.entity.PageResult;
import org.answer.entity.QueryPageBean;
import org.answer.entity.Result;
import org.answer.pojo.Setmeal;
import org.answer.service.BehaviorLogService;
import org.answer.service.SetmealService;
import org.answer.utils.BehaviorLogUtils;
import org.answer.utils.GetUserNameUtils;
import org.answer.utils.DateUtils;
import org.answer.utils.ErrorMailUtils;
import org.answer.utils.QiniuUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;



/**
 * 套餐管理
 */

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    //log4j日志对象
    private Logger logger = ErrorMailUtils.getLogger();

    //    使用JedisPool操作Redis服务
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private SetmealService setmealService;

    @Reference
    private BehaviorLogService behaviorLogService;

    //文件上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest request){
        String originalFilename = imgFile.getOriginalFilename();//原始文件名 3bd90d2c-4e82-42a1-a401-882c88b06a1a2.jpg
        int index = originalFilename.lastIndexOf(".");
        String extention = originalFilename.substring(index - 1);//扩展名 .jpg
        String fileName = UUID.randomUUID().toString() + extention;//	FuM1Sa5TtL_ekLsdkYWcf5pyjKGu.jpg
        try {
            //将文件上传到七牛云服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }


    //新增套餐
    @PreAuthorize("hasAuthority('SETMEAL_ADD')") //  权限校验
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds, HttpServletRequest request){
        List<Setmeal> list = setmealService.findAll();

        try{
            for (Setmeal setMeal : list) {
                if ( setMeal.getCode().equals(setmeal.getCode())){
                    return new Result(false, "当前套餐编码已占用，请输入其他编码！");
                }
            }
            setmealService.add(setmeal,checkgroupIds);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    //分页查询
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')") //  权限校验
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){

        return setmealService.pageQuery(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),queryPageBean.getQueryString());
    }


    //删除
    @PreAuthorize("hasAuthority('SETMEAL_DELETE')") //  权限校验
    @RequestMapping("/delete")
    public Result delete(Integer id, HttpServletRequest request) {
        try {
            setmealService.deleteById(id);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.DELETE_SETMEAL_SUCCESS
                    )
            );
            return new Result(true, MessageConstant.DELETE_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.DELETE_SETMEAL_FAIL
                    )
            );
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.DELETE_SETMEAL_FAIL);
        }
    }

//    编辑

    /**
     * 通过id查询对应的Setmeal对象
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Setmeal setmeal = setmealService.findById(id);
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

//    根据套餐ID查询套餐包含的多个检查组ID
    @RequestMapping("/findCheckGroupIdsBySetmealId")
    public Result findCheckGroupIdsBySetmealId(Integer id){
        try {
            List<Integer> checkGroupIds = setmealService.findCheckGroupIdsBySetmealId(id);
            return new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS,checkGroupIds);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
    }

    //   编辑套餐
    @PreAuthorize("hasAuthority('SETMEAL_EDIT')") //  权限校验
    @RequestMapping("/edit")
   public Result edit(@RequestBody Setmeal setmeal,Integer[] checkgroupIds, HttpServletRequest request){
        List<Setmeal> list = setmealService.findAll();
        Integer id = setmeal.getId();
        String oldCode = setmealService.findById(id).getCode();
        try {
            if (setmeal.getCode().equals(oldCode)){
                setmealService.edit(setmeal, checkgroupIds);
                behaviorLogService.add(
                        BehaviorLogUtils.getBehaviorLog(
                                GetUserNameUtils.getUsername(),
                                request.getRequestURL().toString(),
                                MessageConstant.EDIT_SETMEAL_SUCCESS
                        )
                );
            }else {
                for (Setmeal setMeal : list) {
                    if (setMeal.getCode().equals(setmeal.getCode())){
                        return new Result(false, "当前套餐编码已占用，请输入其他编码！");
                    }

                }
                setmealService.edit(setmeal, checkgroupIds);
                behaviorLogService.add(
                        BehaviorLogUtils.getBehaviorLog(
                                GetUserNameUtils.getUsername(),
                                request.getRequestURL().toString(),
                                MessageConstant.EDIT_SETMEAL_SUCCESS
                        )
                );
            }
       } catch (Exception e) {
           e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.EDIT_SETMEAL_FAIL
                    )
            );
           return new Result(false,MessageConstant.EDIT_SETMEAL_FAIL);
       }
        return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
   }

}
